package com.example.demo.utils;
import com.alibaba.fastjson.JSON;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.Objects;

/**
 * 缓存提供类
 */
public class CacheProvider {

    //由于当前class不在spring boot框架内（不在web项目中）所以无法使用autowired，使用此种方法进行注入
    private static RedisTemplate<String, String> template = (RedisTemplate<String, String>) SpringBeanUtil.getBean("redisTemplate");

    public static <T> boolean set(String key, T value) {
        return set(key, JSON.toJSONString(value), null);
    }

    public static boolean set(String key, String value, Long validTime) {
        return template.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = template.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                if (validTime != null) {
                    connection.expire(serializer.serialize(key), validTime);
                }
                return true;
            }
        });
    }

    public static <T> T get(String key, Class<T> clazz) {
        return JSON.parseObject(get(key), clazz);
    }

    public static String get(String key) {
        return template.execute(new RedisCallback<String>() {
            @SuppressWarnings("NullableProblems")
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = template.getStringSerializer();
                byte[] value = connection.get(Objects.requireNonNull(serializer.serialize(key)));
                return serializer.deserialize(value);
            }
        });
    }

    public static boolean del(String key) {
        return template.delete(key);
    }
}
